//
//  YWJointPuzzleController.m
//  YWPhotoEditMaster
//
//  Created by jun peng on 2023/8/29.
//

#import "YWJointPuzzleController.h"
#import "YWPuzzleStatus.h"
#import "YWJointPuzzleCell.h"

@interface YWJointPuzzleController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *bgView;

@property(nonatomic,strong)NSMutableArray *puzzleArray;

@property(nonatomic,strong)UICollectionView *collectionView;

@property(nonatomic,weak)YWJointPuzzleCell *longPressCell;
@property(nonatomic,weak)UILongPressGestureRecognizer *longPressRecognizer;

@property(nonatomic,strong)UIImageView *panImageView;

@end

@implementation YWJointPuzzleController

//一、做拼接拼图有三种方案、
//1、华人 / 模板拼图的collectionView主动方法、
//2、投资快报collectionView的代理被动方法、
//3、股扒扒的tableView的移动方案
//二、现在我拼接拼图目前用的是“投资快报的栏目排序方式”、它这个好处是contentOffset系统会自动帮我移动（其它两个都不能）
//三、移动过程中它不能马上改变cell的高度、最好办法是不用collectionView而是自定义scrollView上add图片、或者看看瀑布流自定义layout来确定图片高度、不要等到代理方法才获取高度不然来不及动态改变移动图片的高度


static NSString * const cellID = @"YWJointPuzzleCell";
-(NSMutableArray *)puzzleArray{
    if(_puzzleArray == nil){
        _puzzleArray = [NSMutableArray array];
    }
    return _puzzleArray;
}


-(UIImageView *)panImageView{
    if(_panImageView == nil){
        
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self.collectionView addSubview:imageView];
        imageView.hidden = YES;
        _panImageView = imageView;
        
    }
    return _panImageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"YWFreedomPuzzleController:%ld",self.photos.count);
    NSLog(@"YWFreedomPuzzleController:%ld",self.assets.count);
    
    NSMutableArray *mArray = [NSMutableArray array];
    for (UIImage *image in self.photos) {
        YWPuzzleStatus *status = [[YWPuzzleStatus alloc] init];
        status.image = image;
        [mArray addObject:status];
    }
    self.puzzleArray = mArray;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[[UICollectionViewFlowLayout alloc]init]];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    [self.bgView addSubview:collectionView];
    
    [collectionView registerNib:[UINib nibWithNibName:@"YWJointPuzzleCell" bundle:nil] forCellWithReuseIdentifier:cellID];
    
    collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView = collectionView;
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlepanGesture:)];
    longPress.minimumPressDuration = 0.1;
    [_collectionView addGestureRecognizer:longPress];
    self.longPressRecognizer = longPress;
    
    MJWeakSelf
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.bgView);
    }];
    
}


-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.puzzleArray.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    YWPuzzleStatus *status = self.puzzleArray[indexPath.item];
    
    YWJointPuzzleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    
    cell.status = status;
    
    cell.backgroundColor = [UIColor whiteColor];
    
    return cell;
    
}


-(UIImage *)getCurrentLayer{
    
//    //1.开启一个位图上下文
//    UIGraphicsBeginImageContextWithOptions(self.bgView.size, NO, 0);
//
//    //2.把画板上的内容渲染到上下文当中
//    CGContextRef ctx =  UIGraphicsGetCurrentContext();
//    [self.bgView.layer renderInContext:ctx];
//
//    //3.从上下文当中取出一张图片
//    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//
//    //4.关闭上下文
//    UIGraphicsEndImageContext();
    
    return [self screenShotForIndexPaths];
}


//定义每个UICollectionViewCell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YWPuzzleStatus *status = self.puzzleArray[indexPath.item];
    
    return CGSizeMake(self.collectionView.width, self.collectionView.width / status.image.size.width * status.image.size.height);
}

//定义每个UICollectionView的内边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//设置垂直间距,默认的垂直和水平间距都是0
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

//设置水平间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}



//长按手势拖拽排序
- (void)handlepanGesture:(UIPanGestureRecognizer *)panGesture {
    
    //判断手势状态
    switch (panGesture.state) {
            
            //一开始拖拽
        case UIGestureRecognizerStateBegan:{
            
            //判断手势落点位置是否在路径上
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[panGesture locationInView:self.collectionView]];
            
            //假如不是在indexPath范围内的，直接返回
            if (indexPath == nil) {
                break;
            }
            
            YWJointPuzzleCell *cell = (YWJointPuzzleCell*)[self.collectionView cellForItemAtIndexPath:indexPath];
            
            self.longPressCell = cell;
            
            cell.hidden = YES;
            self.panImageView.hidden = NO;
            
            self.panImageView.image = cell.imageView.image;
            self.panImageView.frame = cell.frame;
            
            CGSize imageSize = cell.imageView.image.size;
            CGFloat W = Wi;
            CGFloat H = W / imageSize.width * imageSize.height;
            [UIView animateWithDuration:0.2 animations:^{
                
                self.panImageView.center = [panGesture locationInView:self.collectionView];
                self.panImageView.bounds = CGRectMake(0, 0, W, H);
            }];
            
            //在路径上则开始移动该路径上的cell
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
        case UIGestureRecognizerStateChanged:{
            
            self.panImageView.center = [panGesture locationInView:self.collectionView];
            
            //移动过程当中随时更新cell位置
            [self.collectionView updateInteractiveMovementTargetPosition:[panGesture locationInView:self.collectionView]];
            
        }
            break;
        case UIGestureRecognizerStateEnded:{
        
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[panGesture locationInView:self.collectionView]];
            
            YWLog(@"indexPath:%ld",indexPath.item);
            
//            YWPuzzleStatus *status = self.puzzleArray[indexPath.item];
//            CGSize imageSize = status.image.size;
            
            CGFloat x = 0;
            CGFloat w = Wi;
//            CGFloat h = w * 1.0 / imageSize.width * imageSize.height;
            CGFloat h = self.panImageView.height;
            CGFloat y = 0;
            
            for (NSInteger i = 0; i < indexPath.item; i++) {
                
                YWPuzzleStatus *status2 = self.puzzleArray[i];
                CGSize imageSize2 = status2.image.size;
                CGFloat w2 = Wi;
                CGFloat h2 = w2 * 1.0 / imageSize2.width * imageSize2.height;
                y = y + h2;
            }
            
            
            
            [UIView animateWithDuration:0.2 animations:^{
                
                self.panImageView.frame = CGRectMake(x, y, w, h);
                
            } completion:^(BOOL finished) {
                
                self.panImageView.hidden = YES;
                self.longPressCell.hidden = NO;
                
                //移动结束后关闭cell移动
                [self.collectionView endInteractiveMovement];
                
            }];
            
        }
            break;
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

//是否允许移动
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    //返回YES允许其item移动
    return YES;
}

//当手势移动成功后会调用这个方法 ，这个方法用来改变模型，因为在手势里一直都是改变样式并没有改变模型
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    
    //拿出改变的模型
    YWPuzzleStatus *imageStatus = [self.puzzleArray objectAtIndex:sourceIndexPath.item];
    
    //两个数组都要改变模型
    NSMutableArray *mArray = [NSMutableArray arrayWithArray:self.puzzleArray];

    [mArray removeObject:imageStatus];

    [mArray insertObject:imageStatus atIndex:destinationIndexPath.item];

    self.puzzleArray = mArray;
    
    [UIView transitionWithView:self.collectionView duration:0.1 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        
        [self.collectionView reloadData];
                      
    } completion:^(BOOL finished) {
   
                      
    }];
    
    
}


//保存长图方法：https://www.jianshu.com/p/b20574425d56
- (UIImage*)screenShotForIndexPaths{
    
    
    CGFloat height = 0;
    CGFloat width = Wi;
    for (NSInteger i = 0; i < self.puzzleArray.count; i++ ) {
        YWPuzzleStatus *status = self.puzzleArray[i];
        CGSize imageSize = status.image.size;
        CGFloat h = width * 1.0 / imageSize.width * imageSize.height;
        height = h + height;
    }
    
    CGSize size = CGSizeMake(width, height);

    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    //绘制表头

    CGContextTranslateCTM(ctx, 0, 0); //y轴移动0的位置

    //---一個一個把cell render到CGContext上
    CGFloat y = 0;
    for(int i = 0;i < self.puzzleArray.count;i++)

    {
        
        YWJointPuzzleCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
        YWPuzzleStatus *status = self.puzzleArray[i];
        cell.status = status;
        
        
        CGSize imageSize = status.image.size;
        CGFloat width = Wi;
        CGFloat height = width * 1.0 / imageSize.width * imageSize.height;
        cell.frame = CGRectMake(0, y, width, height);
        
        y = y + height;
        
        [cell.contentView.layer renderInContext:ctx];

        //绘制cell

        CGContextTranslateCTM(ctx, 0, height); //向下移动height继续绘图

    }


    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();


    UIGraphicsEndImageContext();


    return image;

}

@end
